const { Trans } = require('./base');
const _ = require('lodash');

const clone = obj => (JSON.parse(JSON.stringify(obj)));

const getMaxLength = arr => (arr.reduce((prev, curr) => {
    let l = curr.some(item => item >= 10) + curr.length
    return Math.max(prev, l)
}, 0) * 2 - 1);

const printTable = (arr, h, v) => {
    let vMax = getMaxLength(v), hMax = h.reduce((prev, curr) => (Math.max(prev, curr.length)), 0);

    let leftPad = vMax + 2;

    let topLine = ""

    for (let i = 0; i < hMax; i++) {
        topLine += _.repeat(" ", leftPad) + h.map(item => i + item.length < hMax ? " " : item[i + item.length - hMax]).join(' ') + "\n"
    }

    return topLine + "\n" + arr.map((line, index) => (_.padStart(v[index].join(' '), vMax) + '  ' + line.map(item => (Trans[item])).join(' '))).join('\n')
}

const printLine = arr => {
    return arr.join(' ') + " ";
}

const init = () => {
    let res = new Array(10).fill(null);
    for (let i = 0; i < res.length; i++) {
        res[i] = new Array(10).fill(0)
    }

    return res;
}

const fill = (arr, val, pos) => {
    if (arr[pos] === val || pos < 0 || pos > arr.length - 1) {
        return;
    }
    if (arr[pos] === 0) {
        arr[pos] = val;
    } else {
        throw (`Error happened when filling a [${val}] to [${pos}] in [${printLine(arr)}].`)
    }
}

const fillRange = (arr, val, start = 0, end) => {
    if (end !== 0 && !end) {
        end = arr.length - 1;
    }
    if (start > end) {
        return;
    }
    for (let i = start; i <= end; i++) {
        fill(arr, val, i);
    }
}

const isWin = arr => {
    return arr.every(line => line.indexOf(0) === -1);
}

module.exports = {
    clone,
    getMaxLength,
    printTable,
    printLine,
    init,
    fill,
    fillRange,
    isWin
}